
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Vector;


public class Updater extends Thread{
	
	Connection myConnection;
    Statement statement = null;
    ResultSet rs = null;
    Vector<Integer> userList = ClientHandler.userList;
    private int updatedListSize;
    private int notUpdating = 0;
    
    public Updater(Connection myConnection, String name){
    	this.myConnection = myConnection;
    	this.setName(name);
    	buildUserList();
    }
    
	@Override
	public void run(){
		while(true){
			int index = updatedListSize;
			String empty = "";
			Timestamp ts = Timestamp.valueOf("2011-01-01 00:00:00");
			while(index < userList.size()){
				try {
					int userId = userList.get(index);
					statement = myConnection.createStatement();
					statement.executeUpdate("INSERT INTO user VALUES ('"+userId+"', '"+empty+"','"+empty+"','"+empty+"','"+empty+"', '"+empty+"' , '"+ts+"' , '"+notUpdating+"')");
					index++;
				} catch (SQLException e) {
					System.err.println("Duplicate entry by user");
				}
			}
			updatedListSize = index;
			synchronized(userList){
				try {
					System.out.println("nothing to update more, " + Thread.currentThread().getName() + " is waiting!!");
					userList.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * building the user id List in Server from the DB
	 */
	public void buildUserList(){
		try {
			statement = myConnection.createStatement();
			rs = statement.executeQuery("SELECT id FROM user");
			while(rs.next()){
				userList.add(rs.getInt(1));
			}
			updatedListSize = userList.size();
			System.out.println("No. of users in DB: " + userList.size());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
